package com.ylz.sjzx.sio.sdk.client.core;

import com.ylz.sjzx.sio.common.core.core.IAdapter;
import com.ylz.sjzx.sio.common.core.core.Interceptor.InterceptorChain;
import com.ylz.sjzx.sio.common.core.core.SioBase;
import com.ylz.sjzx.sio.common.core.core.container.ContainerManager;
import com.ylz.sjzx.sio.common.core.utils.GsonUtil;
import com.ylz.sjzx.sio.sdk.client.session.IMSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author wiqi
 * @version 1.0
 * @date 2020/12/9
 */
public abstract class AbstractBaseAdapter implements IAdapter {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 抽象类
     *
     * @return
     */
    @Override
    public abstract void process() throws Exception;

    @Override
    public void invoke() {
        //拦截器
        InterceptorChain interceptorChain = ContainerManager.getInterceptorChain();
        try {
            //拦截器处理
            interceptorChain.preHandle();
            //业务处理
            this.process();

            //后置处理，逆序执行拦截器
            interceptorChain.postHandle();
        } catch (Throwable e) {
            this.logger.error("netty adapter-service exception -Error param:{}user:{}", SioBase.getParam(),
                    IMNioBase.getSession(), e);
            //吃掉异常
            SioBase.setException(e);
            Optional.ofNullable(IMNioBase.getSession()).map(IMSession::getSocketIOClient).ifPresent(socket -> {
                this.logger.error("request url?{}", socket.getHandshakeData().getUrlParams());
            });
        } finally {
            interceptorChain.afterCompletion();
        }
    }

    /**
     * 获取session
     *
     * @return
     */
    public IMSession getSession() {
        return IMNioBase.getSession();
    }

    /**
     * 获取param
     * 注：用getFirstParam 替代
     *
     * @return
     */
    @Deprecated
    public <T> T getParam(Class<T> clazz) {
        return GsonUtil.json2Bean(SioBase.getParam().toString(), clazz);
    }

    /**
     * 获取param
     *
     * @return
     */
    public Object getParam() {
        return SioBase.getParam();
    }

    /**
     * 获取param
     *
     * @return
     */
    public Object getFirstParam() {
        List param = (List) SioBase.getParam();
        return param.get(0);
    }

    /**
     * 获取param
     *
     * @return
     */
    public <T> T getFirstParam(Class<T> clazz) {
        List param = (List) SioBase.getParam();
        return GsonUtil.json2Bean(param.get(0).toString(), clazz);
    }

    public <T> T getParamMap(Class<T> clazz) {
        List param = (List) SioBase.getParam();
        return GsonUtil.json2Bean(param.get(0), clazz);
    }

    /**
     * 获取param
     *
     * @return
     */
    public Map getMapParam() {
        return (Map) SioBase.getParam();
    }

}
